<?php

namespace app\api\controller\app;

use app\admin\model\Org;
use app\admin\model\Userarea;
use app\admin\model\Userfx;
use app\admin\model\Userweixin;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['auth'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function auth(){



        $config = [
            'app_id' => "wx219c04bc2cd4aadf",
            'secret' => "d9dd4c93015fce0b3fe4db3626551da3",
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];

        error_log("=====auth======".json_encode($config));
        $app = Factory::miniProgram($config);

        $code = $this->request->param('code');
        $phoneData = $this->request->param('phoneData');
        $phoneIv = $this->request->param('phoneIv');

        $ret = $app->auth->session($code);
        if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
            $this->error('请重新获取code');
        } else {
            $openid = $ret['openid'];
            $session_key = $ret['session_key'];
            $userWeixinModel = new Userweixin();
            $userwx = $userWeixinModel->where('openid', $openid)->find();
            if ($userwx) {
                $ret = $this->auth->direct($userwx['user_id']);
                $userModel = new \app\admin\model\User();
                $user = $userModel->where('id', $userwx['user_id'])->find();
                $phoneNumber = $user['mobile'];
                $ret = $this->auth->direct($user['id']);
                $token = $this->auth->getToken();
                $data = array();
                $data['session_key'] = $session_key;
                $data['token'] = $token;
                if($user['mobile'] == ""){
                    if($phoneIv != "") {
                        $decryptedPhoneData = $app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
                        $phoneNumber = $decryptedPhoneData['phoneNumber'];
                        $userModel->where('id',$user['id'])->update(['mobile'=>$phoneNumber]);
                    }
                }
                $avatar = $user['avatar'];
                if($avatar != ''){
                    $avatar = cdnurl($avatar,true);
                }
                $data['avatar'] = $avatar;
                $data['mobile'] = $phoneNumber;
                $data['username'] = "微信用户";
                $this->success('登录成功', $data);

            } else {

                $userModel = new \app\admin\model\User();

                if($phoneIv != ""){
                    $decryptedPhoneData = $app->encryptor->decryptData($session_key, $phoneIv, $phoneData);
                    $phoneNumber = $decryptedPhoneData['phoneNumber'];
                    $isFindUser = $userModel->where('mobile', $phoneNumber)->find();
                    if ($isFindUser) {
                        $id = $isFindUser['id'];
                    }else{
                        $db = array();
                        $db['group_id'] = 1;
                        $db['username'] = "微信用户";
                        $db['mobile'] = $phoneNumber;
                        $db['createtime'] = time();
                        $db['status'] = 'normal';

                        $id = $userModel->insertGetId($db);
                    }
                }else{
                    $phoneNumber = "";

                    $db = array();
                    $db['group_id'] = 1;
                    $db['username'] = "微信用户";
                    $db['mobile'] = "";
                    $db['createtime'] = time();
                    $db['status'] = 'normal';


                    $id = $userModel->insertGetId($db);
                }

                $userWeixinModel->insert(['user_id'=>$id,'openid'=>$openid]);
                $ret = $this->auth->direct($id);
                $token = $this->auth->getToken();

                $data = array();
                $avatarUrl = "";
                $data['session_key'] = $session_key;
                $data['token'] = $token;
                $data['avatar'] = $avatarUrl;
                $data['username'] = "微信用户";
                $data['mobile'] = $phoneNumber;

                $this->success('登录成功', $data);

            }


        }
    }


    public function teamList(){


        $page = $this->request->param('page');
        $limit = 300;
        $offset = ($page - 1) * $limit;

        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();


        $where = array();
        $where["ref_uid"] =$user['id'];
        $list = $userModel->field('id,group_id,username,mobile,ref_uid,avatar')->where($where)->limit($offset,$limit)->select();

        $userAreaModel = new Userarea();

        foreach ($list as $key=>$val){
            $list[$key]['create_time'] = date("Y-m-d",time());

            if($val['avatar'] == ''){
                $list[$key]['avatar'] = "";
            }else{
                $list[$key]['avatar'] = cdnurl($val['avatar'],true);

            }
            $area = $userAreaModel->where('user_id',$val['id'])->find();
            $str = "";
            if($area){
                $str = " | 区县代理";
            }
            if($val['group_id'] == 2){
                $list[$key]["group_name"] = "分销商".$str;
            }else{
                $list[$key]["group_name"] = "会员".$str;
            }
        }

        $this->success('',$list);

    }


    public function info(){


        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$user['id'])->find();


        $ret = array();
        $ret['username'] = $user['username'];
        $ret['mobile'] = $user['mobile'];
        if($user['avatar'] != ""){
            $ret['avatar'] = cdnurl($user['avatar'],true);
        }else{
            $ret['avatar'] = "";

        }

        $this->success('',$ret);
    }






    public function updateUserInfo(){

        $avatar = $this->request->param('avatar');
        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $userModel->where('id',$user['id'])->update(['avatar'=>$avatar]);

        $this->success('成功');
    }




}
